﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Eqwww.Config;
using Eqwww.App.Authorize;
using Eqwww.Domain.Models.SystemManage;

namespace Eqwww.Web.Areas.SystemManage.Controllers
{
    [Area("SystemManage")]
    public class ConfigManageController : ControllerBase
    {
        private IAppConfigProvider _appConfigProvider;
        private IEmailConfigProvider _emailConfigProvider;
        private AuthorizeApp _authorizeApp;

        public ConfigManageController(IAppConfigProvider appConfigProvider
            ,AuthorizeApp authorizeApp
            ,IEmailConfigProvider emailConfigProvider)
        {
            _emailConfigProvider = emailConfigProvider;
            _authorizeApp = authorizeApp;
            _appConfigProvider = appConfigProvider;
        }


        [AuthFilter]
        public IActionResult Index()
        {
            var currentModuleCode = "SystemManage_ConfigManage";
            ViewData["SelectedButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Selected);
            ViewData["InitialButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Initial);

            return View();
        }

        [AuthFilter]
        public IActionResult AppConfigForm()
        {
            var appConfig = _appConfigProvider.Load();
            return View(appConfig);
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult AppConfigSubmit(AppConfig appConfig)
        {
            _appConfigProvider.Save(appConfig);
            return Success("操作成功");
        }

        [AuthFilter]
        public IActionResult EmailConfigForm()
        {
            var config = _emailConfigProvider.Load();
            return View(config);
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult EmailConfigFormSubmit(EmailConfig appConfig)
        {
            if (ModelState.IsValid)
            {
                _emailConfigProvider.Save(appConfig);
                return Success("操作成功");
            }
            return Json(Eqwww.Code.Common.ModelStateErrorResult(ModelState));
        }

    }
}